require 'account/account.rb'
require 'digest/sha1'


# アカウント操作ヘルパ
#
# Author:: krdlab
#
# TODO 加工
# self.ticket = create_ticket
# self.expiration = 
class AccountHelper

	L_NAME = 'login_id'
	L_PASS = 'login_password'

	def initialize(cgi, session)
		@cgi = cgi
		@session = session
	end

	def new_account
		# TODO 異常値対応
		ac = Account.new(
			:name => get_parameter(L_NAME),
			:password => to_digest(get_parameter(L_PASS)),
			:ticket => create_ticket
		)
		ac.save
		set_session('ticket', ac.ticket)
		true
	end

	def login
		ac = get_account
		if not ac.nil? then 
			true
		end

		dg = to_digest(get_parameter(L_PASS))
		ac = Account.find(:first,
					:conditions => ["password = ?", dg])
		if not ac.nil? then
			set_session('ticket', ac.ticket)
			true
		else
			set_session('ticket', nil)
			false
		end
	end

	def logout
		ac = get_account
		if not ac.nil? then
			ac.update_attribute(:ticket, nil)
			set_session('ticket', nil)
		end
		true
	end

	def get_account
		ticket = get_session('ticket')
		return Account.find(:first,
					:conditions => ["ticket = ?", ticket])
	end

private
	def get_parameter(name)
		@cgi[name]
	end

	def set_session(name, value)
		@session[name] = value
	end

	def get_session(name)
		@session[name]
	end

	def match_password(raw)
		match_password_digest(to_digest(raw))
	end

	def to_digest(raw)
		Digest::SHA1.digest(raw)
	end

	def match_password_digest(dg)
		self.password == dg
	end

	def create_ticket
		to_digest(Time.now.to_s)
	end
end

